package com.xxl.job.executor.service.jobhandler;

import com.xxl.job.core.log.XxlJobLogger;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

public class HttpServer {

    /**
     * @param url           远程调用路径
     * @param paraMap       参数
     * @param requestMethod 调用方式(GET/POST)
     * @return String
     */
    public static String httpCall(String url, Map<String, String> paraMap, String requestMethod) throws Exception {
        XxlJobLogger.log("------------调度同步测试开始-------------------------");
        // 远程调用接口
        URL restURL = new URL(url);
        // 此处的urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类 的子类HttpURLConnection
        HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
        //设置连接超时时间
        conn.setConnectTimeout(50000);
        //设置读取返回内容超时时间
        conn.setReadTimeout(50000);
        //设置请求方式，默认为GET
        conn.setRequestMethod(requestMethod);
        //设置是否使用缓存，post方式不能使用缓存
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        //请求的参数类型(使用restlet框架时，为了兼容框架，必须设置Content-Type为“”空)
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        //设置是否从httpUrlConnection读入，默认情况下是true; httpUrlConnection.setDoInput(true);
        conn.setDoOutput(true);
        //allowUserInteraction 如果为 true，则在允许用户交互（例如弹出一个验证对话框）的上下文中对此 URL 进行检查。
        conn.setAllowUserInteraction(false);
//        conn.connect();
        PrintStream ps = new PrintStream(conn.getOutputStream());
        String paramStr = getParams(requestMethod,paraMap);
        ps.print(paramStr);
        ps.close();
        BufferedReader bReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line, resultStr = "";
        while (null != (line = bReader.readLine())) {
            resultStr += line;
        }
        bReader.close();
        XxlJobLogger.log("调用远程接口后的返回结果集String---" + resultStr);
        return resultStr;
    }

    /**
     * 得到参数列表字符串
     *
     * @param method      请求类型 GET or  POST
     * @param paramValues 参数map对象
     * @return 参数列表字符串
     */
    public static String getParams(String method, Map<String, String> paramValues) {
        String params = "";
        Set<String> keys = paramValues.keySet();
        String beginLetter = "";
        if (method.equalsIgnoreCase("GET")) {
            beginLetter = "?";
        }

        for (Iterator<String> it = keys.iterator(); it.hasNext(); ) {
            String key = it.next();
            if (params.equals("")) {
                params += beginLetter + key + "=" + paramValues.get(key);
            } else {
                params += "&" + key + "=" + paramValues.get(key);
            }
        }
        return params;
    }

    /**
     * 按照key排序得到参数列表字符串
     *
     * @param method      请求类型 GET or  POST
     * @param paramValues 参数map对象
     * @return 参数列表字符串
     */
    public static String getParamsOrderByKey(String method, Map<String, String> paramValues) {
        String params = "";
//        Set<String> keys = paramValues.keySet();
        String beginLetter = "";
        if (method.equalsIgnoreCase("GET")) {
            beginLetter = "?";
        }
        List<String> paramNames = new ArrayList<String>(paramValues.size());
        paramNames.addAll(paramValues.keySet());
        Collections.sort(paramNames);
        for (String paramName : paramNames) {

            if (params.equals("")) {
                params += beginLetter + paramName + "=" + paramValues.get(paramName);
            } else {
                params += "&" + paramName + "=" + paramValues.get(paramName);
            }
        }
        return params;
    }


}
